// eslint-disable-next-line
import { Upload, Button, Card, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';//引入获取跳转携带的参数 方法
import UserApi from '../../api/user';
import { useEffect } from 'react';
import { useHistory } from "react-router";
import { useAddress } from '../../hook/address';

// eslint-disable-next-line import/no-anonymous-default-export
export default () => {
  const history = useHistory();
  const params = useParams();
  const { _id } = params
  const token = UserApi.getToken;
  const [{ oneAddr }, { getOneAddress, removeImg }] = useAddress();

  useEffect(() => {
    getOneAddress(_id); // 直接调用hook里面传过来的数据
  }, [getOneAddress, _id])

  const props = {
    uid: '',
    name: 'file',//文件名
    action: '/resource/address/:_id',//请求到资源服务器的地址
    status: 'done',//上传状态
    headers: { authorization: 'authorization-text' },//上传进度
    //data 是自定义需要的一些额外参数
    data: {
      _id: _id, token: token
    },
    // 提示
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功,即将跳转首页`, () => {
          history.push(`/info/address`)
        });
      }
    }
  }

  // // 删除
  const onRemove = async ({ url }) => {
    // replace 替换 把路径替换成空串
    const newUrl = url.replace("http://localhost:3002", "")
    await removeImg({ _id, url: newUrl })
  }

  return (
    <div style={{ background: ' #ececec', width: '100%', minHeight: "100%", display: 'flex' }}>
      <Card title="上传图片" bordered={false} style={{ width: 400, margin: 'auto', }}>
        <Upload {...props}
          listType="picture"//上传列表的类型 
          multiple={true} //多文件上传
          // 已经上传的文件列表（受控）
          defaultFileList={
            oneAddr.imgs ? [
              {
                uid: '-1',
                name: oneAddr.imgs,
                status: 'done',
                url: `http://localhost:3002${oneAddr.imgs}`,
                thumbUrl: `http://localhost:3002${oneAddr.imgs}`,
              }
            ] : []
          }
          onRemove={onRemove}
        >
          <Button icon={<UploadOutlined />}>点击上传</Button>
        </Upload>
      </Card>
    </div >
  )
}